#!/usr/bin/env bash
# Dark Factory pre-push gate -- blocks push if any pushed commit has
# unresolved blockers in its critic artifact. Reads git's pre-push
# protocol on stdin and consults the per-SHA artifacts written by
# `df review` in the post-commit hook. Free: no LLM calls here.
#
# Implements the consumer-shape adoption pattern documented in
# `@momentiq/dark-factory-cli` README and `momentiq-ai/dark-factory`
# `docs/CONSUMER-ADOPTION.md` § 3. Replaces the previous embedded
# `tools/agent-review/` shim shipped through sage-blueprint BP-10
# (see BP-N Dark-Factory-Consumer cycle).
#
# Emergency bypass:
#   AGENT_REVIEW_BYPASS="<reason>" git push
# The reason is logged to `.git/agent-reviews/_runs.ndjson` for audit
# (`df stats` surfaces it).

set -euo pipefail

# Capture pre-push stdin once so we can feed it to the CLI.
STDIN_BUF="$(cat)"

# Bypass: works even if the CLI is missing (that's the definition of an
# emergency). Write telemetry from the hook itself so the bypass remains
# auditable. JSON-safe escape: strip control chars + escape \ and ".
if [[ -n "${AGENT_REVIEW_BYPASS:-}" ]]; then
  echo "df: pre-push gate BYPASSED -- reason: ${AGENT_REVIEW_BYPASS}" >&2
  COMMON_DIR="$(git rev-parse --git-common-dir 2>/dev/null || echo .git)"
  TELEMETRY_FILE="${COMMON_DIR}/agent-reviews/_runs.ndjson"
  mkdir -p "$(dirname "${TELEMETRY_FILE}")"
  TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  ESC_REASON=$(printf '%s' "${AGENT_REVIEW_BYPASS}" | tr -d '[:cntrl:]' | sed 's/\\/\\\\/g; s/"/\\"/g')
  printf '{"ts":"%s","event":"gate_bypassed","source":"pre-push-hook","reason":"%s"}\n' \
    "${TS}" "${ESC_REASON}" >> "${TELEMETRY_FILE}"
  exit 0
fi

CLI="./node_modules/.bin/df"
if [[ ! -x "${CLI}" ]]; then
  echo "df: BLOCKED -- CLI not installed at ${CLI}; run 'npm install'." >&2
  echo "df: push with AGENT_REVIEW_BYPASS=\"reason\" only in genuine emergencies." >&2
  exit 1
fi

# `df gate-push` reads git's pre-push protocol on stdin and evaluates
# each commit in the pushed range against its per-SHA artifact.
printf '%s' "${STDIN_BUF}" | "${CLI}" gate-push --profile local
